package com.file.demo.controller;

import com.file.demo.pojo.UserEntity;
import com.file.demo.utils.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Value("${filepath}")
    private String filepath;

    /**
     * 处理文件上传
     */
    @PostMapping(value = "/upload")
    public String uploading(@RequestParam("file") MultipartFile file) {
        File targetFile = new File(filepath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try (FileOutputStream out = new FileOutputStream(filepath + file.getOriginalFilename());){
            out.write(file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件上传失败!");
            return "uploading failure";
        }
        log.info("文件上传成功!");
        return "uploading success";
    }

    @RequestMapping("/download")
    public void downLoad(HttpServletResponse response,@RequestParam("filename") String filename) throws UnsupportedEncodingException {
        File file = new File(filepath + "/" + filename);
        if(file.exists()){
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename,"utf8"));
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try(FileInputStream fis= new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    SimpleDateFormat sdf=new SimpleDateFormat("/yyyy-MM-dd/");
    @PostMapping("/ajaxUpload")
    public String file(MultipartFile file, HttpServletRequest request){
        String format =  sdf.format(new Date());
        String realPath =filepath + format;
        //创建文件夹路径
        File folder = new File(realPath);
        //如果文件夹已经不存在那么我们就创建一下
        if(!folder.exists()){
            folder.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            file.transferTo(new File(folder,newName));
            String url=format+newName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 删除文件
     * @param filename 文件路径
     * @return 是否成功
     */
    @RequestMapping("/deleteFile")
    public  boolean deleteFile(@RequestParam String filename) {
        boolean flag = false;
        File file = new File(filepath+filename);
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }



    /**
     * Excel导出
     */
    @RequestMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {

        UserEntity user1 = UserEntity.builder().id(1L).userName("张三").age(10).birth(new Date()).build();
        UserEntity user2 = UserEntity.builder().id(2L).userName("小李").age(16).birth(new Date()).build();
        UserEntity user3 = UserEntity.builder().id(3L).userName("小王").age(14).birth(new Date()).build();
        List<UserEntity> userList = Stream.of(user1, user2, user3).collect(Collectors.toList());

        //导出操作
        ExcelUtil.exportExcel(userList, null, "用户", UserEntity.class, "测试用户导出.xlsx", response);

    }

    /**
     * Excel导入
     */
    @PostMapping("importExcel")
    public String importExcel(HttpServletResponse response, @RequestParam("file") MultipartFile file) {
        //解析excel
        List<UserEntity> userList = ExcelUtil.importExcel(file, 0, 1, UserEntity.class);
        //也可以使用String filePath = "xxx.xls";importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass)导入
        System.out.println("导入数据一共【" + userList.size() + "】行");
        System.out.println("导入的数据：" + userList);
        //TODO 保存数据库
        return "Success";
    }



}